<?php

namespace app\api\controller\mycurrency;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\OperateCouponsReceive;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;
use think\Db;
use app\common\model\mycurrency\OperateCoupons as Coupons;

/**
 * 营销 - 优惠券接口
 */
class OperateCoupons extends Api
{
    protected $noNeedLogin = ['couponsList'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 可领取优惠券列表
    */
    public function couponsList(){
        $param = $this->request->param();
        $rule = [
            ['page', 'require|>:0', '请填写当前页|当前页展示数量必须大于0'],
            ['pageSize', 'require|>:0', '请填写每页展示数量|每页展示数量必须大于0'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'status' => Coupons::STATUS_ZHENGCHENG,
            'deletetime' => null,
        ];
        $field = '*';
        $order = 'id desc';
        $list = Coupons::where($where)->limit(($param['page'] - 1) * $param['pageSize'], $param['pageSize'])->field($field)->order($order)->select();
        $num = Coupons::where($where)->count();
        if ($num > $param['page'] * $param['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('',[
            'list' => $list,
            'nextpage' => $nextpage,
        ]);
    }

    /**
     * 优惠券领取
     */
    public function couponsReceive(){
        $param = $this->request->param();
        $rule = [
            ['coupons_id', 'require', '优惠券id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        Db::startTrans();
        try {
            $coupons = Coupons::where(['id' => $param['coupons_id'],'deletetime' => null])->lock(true)->find();
            if (!$coupons){
                throw new Exception('优惠券不存在');
            }
            if($coupons['status'] == Coupons::STATUS_JINGYONG){
                throw new Exception('优惠券被禁止领取');
            }
            if($coupons['receive_start_time'] != null && strtotime($coupons['receive_start_time']) > time()){
                throw new Exception('还未到领取时间');
            }
            if($coupons['receive_end_time'] != null && strtotime($coupons['receive_end_time']) < time()){
                throw new Exception('已过领取时间');
            }
            if($coupons['sruplus'] <= 0){
                throw new Exception('优惠券已被领完');
            }
            $receive_count = OperateCouponsReceive::where(['coupons_id' => $param['coupons_id'],'user_id' => $this->auth->id,'deletetime' => null])->count();//该优惠券已领取数量
            if ($receive_count >= $coupons['receive_number']){
                throw new Exception("每人最多可领取{$coupons['receive_number']}张");
            }
            $increase = [
                'coupons_id' => $coupons['id'],
                'user_id' => $this->auth->id,
                'title' => $coupons['title'],
                'discount_type' => $coupons['discount_type'],
                'discount_ratio' => $coupons['discount_ratio'],
                'use_consumption_limit' => $coupons['use_consumption_limit'],
                'full_reduction_fee' => $coupons['full_reduction_fee'],
                'lijian_fee' => $coupons['lijian_fee'],
                'receive_time' => time(),
                'status' => OperateCouponsReceive::STATUS_WEISHIYONG,
                'createtime' => time(),
            ];
            if ($coupons['use_expire_type'] == Coupons::USE_EXPIRE_TYPE_SHICHANG){//1=领取后N天可用
                $increase['use_start_time'] = time();
                $increase['use_end_time'] = time() + ($coupons['effective_day'] * 86400);
            }elseif ($coupons['use_expire_type'] == Coupons::USE_EXPIRE_TYPE_SHIJIANDUAN){//2=指定时间段可用
                $increase['use_start_time'] = strtotime($coupons['use_start_time']);
                $increase['use_end_time'] = strtotime($coupons['use_end_time']);
            }
            OperateCouponsReceive::create($increase);
            Coupons::where(['id' => $coupons['id']])->setDec('sruplus',1);
            Coupons::where(['id' => $coupons['id']])->setInc('already_out',1);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('领取成功');
    }

    /**
     * 我的优惠券列表
     */
    public function userCouponsList(){
        $param = $this->request->param();
        $rule = [
            ['page', 'require|>:0', '请填写当前页|当前页展示数量必须大于0'],
            ['pageSize', 'require|>:0', '请填写每页展示数量|每页展示数量必须大于0'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'user_id' => $this->auth->id,
            'deletetime' => null,
        ];
        if($param['status'] != 0){
            $where['status'] = $param['status'];
        }
        $field = '*';
        $order = 'id desc';
        $list = OperateCouponsReceive::where($where)->limit(($param['page'] - 1) * $param['pageSize'], $param['pageSize'])->field($field)->order($order)->select();
        $num = OperateCouponsReceive::where($where)->count();
        if ($num > $param['page'] * $param['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('',[
            'list' => $list,
            'nextpage' => $nextpage,
        ]);
    }

    /**
     * 可用优惠券列表
    */
    public function userAvailableCoupons(){
        $param = $this->request->param();
        $rule = [
            ['amount_money', 'require|>:0', '消费金额不能为空|消费金额必须大于0'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $amount_money = $param['amount_money'];
        $where = [
            'user_id' => $this->auth->id,
            'status' => OperateCouponsReceive::STATUS_WEISHIYONG,
            'use_start_time' => ['<=',time()],
            'use_end_time' => ['>=',time()],
            'deletetime' => null,
        ];
        $list = OperateCouponsReceive::whereOr(function ($query) use ($where){
                $where['discount_type'] = OperateCouponsReceive::DISCOUNT_TYPE_ZHEKOU;
                $query->where($where);
            })
            ->whereOr(function ($query) use ($where,$amount_money){
                $where['discount_type'] = OperateCouponsReceive::DISCOUNT_TYPE_MANJIAN;
                $where['use_consumption_limit'] = ['<=',$amount_money];
                $query->where($where);
            })
            ->whereOr(function ($query) use ($where,$amount_money){
                $where['discount_type'] = OperateCouponsReceive::DISCOUNT_TYPE_LIJIAN;
                $where['lijian_fee'] = ['<=',$amount_money];
                $query->where($where);
            })
            ->field('id,title,discount_type,discount_ratio,use_consumption_limit,full_reduction_fee,lijian_fee,use_start_time,use_end_time')
            ->select();
        $this->success('',$list);
    }


}
